// 内部结构体 与 协议结构体之间的手工转换

package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/m"
	"GameServer/Game/sp"
	"GameServer/globalFunc"
)

func FormatBanUserInfoSp(u *m.User) (info *sp.UserInfo) {
	info = &sp.UserInfo{
		Status:  u.Status,
		BanTime: u.BanTime,
	}
	return
}

func FormatUserInfoSp(u *m.User) (info *sp.UserInfo) {
	info = &sp.UserInfo{
		Uid:     u.Uid.Hex(),
		Number:  u.Number,
		Name:    u.Name,
		Head:    u.Head,
		Gold:    u.Gold,
		Diamond: u.Diamon,
		Energy:  u.Energy,
		Shield:  u.Shield,
		Pos: &sp.PosInfo{
			LockBlockTid: u.Pos.LockBlockTid,
			LayerId:      u.Pos.LayerId,
		},
		MaxPos: &sp.PosInfo{
			LockBlockTid: u.MaxPos.LockBlockTid,
			LayerId:      u.MaxPos.LayerId,
		},
		Star:       u.StarVal(),
		LockBlocks: make([]*sp.LockBlock, 0),
		// Heros:              FormatHerosInfoSps(u.Heros().Heros),
		// Heros:              FormatHeroListSps(u.Heros().GetHeroList()),
		SlotLv:             u.SlotLv,
		UnionId:            u.UnionId,
		EnergyTime:         u.EnergyTime,
		ReqUnionEnergyTime: u.UnionEnergyReqTime,
		Buff: &sp.Buff{
			FireGridRate: u.FireGridRate,
		},
		UnionScore:          u.UnionScore,
		FireGridRate:        u.FireGridRate,
		Platform:            u.Platform,
		AvatarFrame:         u.AvatarFrame,
		AvatarFrameArr:      FormatAvatarFramesArr(u.AvatarFrameArr),
		UserGroup:           u.UserGroup,
		RegisterTime:        u.RegisterTime,
		SuperAccount:        u.SuperAccount,
		IdentifId:           u.IdentifId,
		FirstReChargeStatus: u.FirstReChargeStatus,
		UsedName:            u.UsedName,
		FaceBookId:          u.FaceBookId,
		RenameCd:            u.RenameCd,
	}

	// if val, ok := u.LockBlocks().LockBlocks[u.Pos.LockBlockTid]; ok {
	// 	valT, ok := m.Cache.Get("lockBlock", val.Mid)
	// 	if !ok {
	// 		return
	// 	}
	// 	lockBlock := valT.(*m.LockBlock)
	// 	block := &sp.LockBlock{
	// 		Tid:         lockBlock.Tid,
	// 		Star:        lockBlock.Star,
	// 		Status:      lockBlock.Status,
	// 		Num:         lockBlock.Num,
	// 		OpenGridNum: lockBlock.GridOpenNum,
	// 		GridSum:     lockBlock.GridNum,
	// 		StarNum:     lockBlock.StarNum,
	// 		Story: &sp.Story{
	// 			Tid:     lockBlock.Story.Tid,
	// 			LayerId: lockBlock.Story.LayerId,
	// 			Status:  lockBlock.Story.Status,
	// 		},
	// 	}

	// 	if lockBlock.Tid == u.Pos.LockBlockTid {
	// 		block.Layers = FormartLayerStringSps(lockBlock.Layers)
	// 	}
	// 	info.LockBlocks = append(info.LockBlocks, block)
	// }

	for _, item := range u.LockBlocks().LockBlocks {
		val, ok := m.Cache.Get("lockBlock", item.Mid)
		if !ok {
			continue
		}
		lockBlock := val.(*m.LockBlock)
		block := &sp.LockBlock{
			Tid:         lockBlock.Tid,
			Star:        lockBlock.Star,
			Status:      lockBlock.Status,
			Num:         lockBlock.Num,
			OpenGridNum: lockBlock.GridOpenNum,
			GridSum:     lockBlock.GridNum,
			StarNum:     lockBlock.StarNum,
			Story: &sp.Story{
				Tid:     lockBlock.Story.Tid,
				LayerId: lockBlock.Story.LayerId,
				Status:  lockBlock.Story.Status,
			},
		}

		if lockBlock.Tid == u.Pos.LockBlockTid {
			block.Layers = FormartLayerStringSps(lockBlock.Layers)
		}
		info.LockBlocks = append(info.LockBlocks, block)
	}

	return
}

func FormatUserPosInfoSp(pos *m.PosInfo) (info *sp.PosInfo) {
	info = &sp.PosInfo{
		LockBlockTid: pos.LockBlockTid,
		LayerId:      pos.LayerId,
	}
	return
}

func FormatSimpleUser(u *m.User) (info *sp.SimpleUser) {
	info = &sp.SimpleUser{
		Uid:         u.Uid.Hex(),
		Name:        u.Name,
		Head:        u.Head,
		Gold:        u.Gold,
		Star:        u.StarVal(),
		AvatarFrame: u.AvatarFrame,
	}
	return
}

//newGuildFlag
func FormatSlotUser(p *m.User, u *m.User, newGuildFlag bool) (info *sp.SimpleUser) {
	var val int64 = 30
	gold := int64(float64(u.Gold*val) / float64(100))
	avatarFrame := u.AvatarFrame
	if avatarFrame == 0 {
		avatarFrame = data.AvatarFrameEnum.DefaultFrame
	}
	info = &sp.SimpleUser{
		Uid:         u.Uid.Hex(),
		Name:        u.Name,
		Head:        u.Head,
		Gold:        gold - int64(float64(gold)*float64(u.TheftGoldRate)/float64(100)),
		Star:        u.StarVal(),
		AvatarFrame: avatarFrame,
	}
	if newGuildFlag {
		list, ok := data.GetAllDatas("NewGuildSlotBoxs")
		if !ok {
			return
		}
		var goldNum int64 = 0
		for i, item0 := range list {
			if i == 0 {
				continue
			}
			item := item0.(data.NewGuildSlotBox)
			goldNum += int64(item.Res.Value)
		}
		info.Gold = goldNum
		return
	}

	stpl, ok := data.Get("SlotTheftProportions", uint64(1))
	if ok {
		stProportion := stpl.(data.SlotTheftProportion)
		val = int64(stProportion.Proportion)
	}

	gold = int64(float64(u.Gold*val) / float64(100))
	goldVal := gold - int64(float64(gold*u.TheftGoldRate)/float64(100))

	if p != nil {
		playerSlotLv := uint64(p.SlotLv)
		slotLevel, ok := data.Get("SlotLvMatchSkins", uint64(playerSlotLv))
		if !ok {
			return
		}
		itemSlotLvMatchSkin := slotLevel.(data.SlotLvMatchSkin)
		stealLitmit := int64(itemSlotLvMatchSkin.StealLitmit)
		if goldVal > stealLitmit && stealLitmit != 0 {
			goldVal = stealLitmit
		}
	}

	info.Gold = goldVal
	return
}

func FormartLockBlockSps(lockBlocks map[int64]*m.LockBlock) (r []*sp.LockBlock) {
	r = make([]*sp.LockBlock, 0)
	for _, item := range lockBlocks {
		itemV := item
		r = append(r, FormartLockBlockSp(itemV))
	}
	return
}

func FormartLockBlockSp(lockBlock *m.LockBlock) (info *sp.LockBlock) {
	info = &sp.LockBlock{
		Tid:         lockBlock.Tid,
		Star:        lockBlock.Star,
		Status:      lockBlock.Status,
		Num:         lockBlock.Num,
		OpenGridNum: lockBlock.GridOpenNum,
		GridSum:     lockBlock.GridNum,
		StarNum:     lockBlock.StarNum,
		Story: &sp.Story{
			Tid:     lockBlock.Story.Tid,
			LayerId: lockBlock.Story.LayerId,
			Status:  lockBlock.Story.Status,
		},
	}
	info.Layers = FormartLayerStringSps(lockBlock.Layers)
	return
}

func FormartLayerSp(layer *m.Layer) (info *sp.Layer) {
	info = &sp.Layer{
		Tid:          layer.Tid,
		GridList:     FormartGridInfoSps(layer.GridList),
		Status:       layer.Status,
		Id:           layer.Id,
		InGridId:     layer.InGridId,
		StoryGridIds: layer.StoryGridIds,
		IsFirstIn:    layer.IsFirstIn,
	}
	return
}

func FormartLayerSps(mLayers map[int64]*m.Layer) (r []*sp.Layer) {
	r = make([]*sp.Layer, 0)
	for _, item := range mLayers {
		itemV := item
		r = append(r, FormartLayerSp(itemV))
	}
	return
}

func FormartLayerStringSps(mLayers map[int64]string) (r []*sp.Layer) {

	r = make([]*sp.Layer, 0)
	for _, item := range mLayers {
		v, ok := m.Cache.Get("layer", item)
		if !ok {
			continue
		}
		layer := v.(*m.Layer)
		r = append(r, FormartLayerSp(layer))
	}
	return

}

func FormartGridInfoSps(list map[int64]*m.GridInfo) (r []*sp.GridInfo) {
	r = make([]*sp.GridInfo, 0)
	for _, item := range list {
		r = append(r, FormartGridInfoSp(item))
	}
	return
}

func FormartGridInfoSp(gridInfo *m.GridInfo) (info *sp.GridInfo) {
	if gridInfo == nil {
		return
	}
	info = &sp.GridInfo{
		Id:          gridInfo.Id,
		Tid:         gridInfo.Tid,
		Status:      gridInfo.Status,
		StatusEx:    gridInfo.StatusEx,
		Head:        gridInfo.Head,
		AvatarFrame: gridInfo.AvatarFrame,
	}

	if gridInfo.Goods == nil {
		return
	}
	info.Goods = &sp.Goods{
		Tid: gridInfo.Goods.Tid,
		Num: gridInfo.Goods.Num,
	}
	return
}

func FormatGoodsInfoSps(goods []*m.Goods) (r []*sp.Goods) {
	if goods == nil || len(goods) <= 0 {
		return
	}
	for _, item := range goods {
		r = append(r, FormatGoodsInfoSp(item))
	}
	return
}

func FormatGoodsInfoSp(goods *m.Goods) (info *sp.Goods) {
	if goods == nil {
		return
	}
	info = &sp.Goods{
		Tid: goods.Tid,
		Num: goods.Num,
	}
	return
}

func FormatHideShopSp(req *m.HideShop) (info *sp.HideShop) {
	info = &sp.HideShop{
		EndTime:   req.EndTime,
		NextTime:  req.NextTime,
		FireNum:   req.FireNum,
		FreshNum:  req.FreshNum,
		LastTime:  req.LastTime,
		IsSpecial: req.IsSpecial,
	}
	if req.Goods == nil || len(req.Goods) <= 0 {
		return
	}
	info.Goods = make([]*sp.HideShopGoods, 0)
	for _, item := range req.Goods {
		info.Goods = append(info.Goods, &sp.HideShopGoods{
			Id:    item.Id,
			Num:   item.Num,
			Goods: FormatGoodsInfoSp(item.Goods),
		})
	}

	if req.AdGoods == nil || len(req.AdGoods) <= 0 {
		return
	}
	info.AdGoods = make([]*sp.HideShopGoods, 0)
	for _, item := range req.AdGoods {
		info.AdGoods = append(info.AdGoods, &sp.HideShopGoods{
			Id:    item.Id,
			Num:   item.Num,
			Goods: FormatGoodsInfoSp(item.Goods),
		})
	}
	return
}

func FormatDailyGiftSp(req *m.DailyGift) (info *sp.DailyGift) {
	if req.Tid == 0 {
		return nil
	}
	info = &sp.DailyGift{
		Tid:     req.Tid,
		CurTime: req.CurTime,
		BuyCnt:  req.BuyCnt,
	}
	return
}

func FormatGiftPacktSp(req *m.GiftPack) (r *sp.GiftPack) {
	packId := int64(0) // packId=0，该礼包已经购买完
	if req.BuyCnt < int64(len(req.PackIdLst)) {
		packId = req.PackIdLst[req.BuyCnt]
	}
	r = &sp.GiftPack{
		Tid:     req.Tid,
		PackId:  packId,
		EndTime: req.EndTime,
	}
	return
}

func FormatGiftPacktSps(req *m.ActPack) (lst []*sp.GiftPack) {
	lst = make([]*sp.GiftPack, 0)
	for _, val := range req.MGiftPack {
		packId := int64(0) // packId=0，该礼包已经购买完
		if val.BuyCnt < int64(len(val.PackIdLst)) {
			packId = val.PackIdLst[val.BuyCnt]
		}
		gp := &sp.GiftPack{
			Tid:     val.Tid,
			PackId:  packId,
			EndTime: val.EndTime,
		}
		lst = append(lst, gp)
	}
	return
}

func FormatBossPacktSps(bp *m.BossPack) (lst []*sp.GiftPack) {
	lst = make([]*sp.GiftPack, 0)
	for _, val := range bp.MGiftPack {
		gp := &sp.GiftPack{
			PackId:  val.PackId,
			EndTime: val.EndTime,
		}
		lst = append(lst, gp)
	}
	return
}

func FormatUnionInfoSps(list []*m.Union) (r []*sp.UnionInfo) {
	for _, item := range list {
		r = append(r, FormatUnionInfoSp(item))
	}
	return
}

func FormatUnionInfoSp(union *m.Union) (info *sp.UnionInfo) {
	return &sp.UnionInfo{
		Id:   union.Id.Hex(),
		Name: union.Name,
		Ico: &sp.UnionIco{
			Bottom: union.Ico.Bottom,
			Pic:    union.Ico.Pic,
		},
		Score:      union.Score,
		Desc:       union.Desc,
		JoinStatus: union.JoinStatus,
		Num:        union.Num,
		ShortName:  union.ShortName,
		Star:       union.Star,
	}
}

func FormatUnionMemberSps(mList map[string]*m.UnionMember) (r []*sp.UnionMember) {
	for _, item := range mList {
		r = append(r, &sp.UnionMember{
			Uid:         item.Uid,
			Name:        item.Name,
			Head:        item.Head,
			Score:       item.Score,
			JoinTime:    item.JoinTime,
			Manager:     item.Manager,
			OnLine:      item.OnLineVal(),
			Star:        item.Star,
			AvatarFrame: item.AvatarFrame,
		})
	}
	return
}

func FormatUnionChatMstSps(list []*m.ChatMsg) (r []*sp.UnionChatMsg) {
	for _, item := range list {
		r = append(r, &sp.UnionChatMsg{
			Mid:  item.Mid,
			Uid:  item.Uid,
			Msg:  item.Msg,
			Time: item.Time,
			Ext:  item.Ext,
			Type: item.Type,
		})
	}
	return
}

func FormatUnionEnergyNoticeSps(list []*m.UnionEnergyRecv) (r []*sp.UnionEnergyNotice) {
	for _, item := range list {
		r = append(r, &sp.UnionEnergyNotice{
			Uid:         item.Uid,
			Name:        item.Name,
			Head:        item.Head,
			EnergyNum:   item.EnergyNum,
			AvatarFrame: item.AvatarFrame,
		})
	}
	return
}

func FormatUnionEnergySendSps(list []*m.UnionEnergySend) (r []*sp.UnionEnergySend) {
	for _, item := range list {
		r = append(r, FormatUnionEnergySendSp(item))
	}
	return
}

func FormatUnionEnergySendSp(val *m.UnionEnergySend) (r *sp.UnionEnergySend) {
	r = &sp.UnionEnergySend{
		Uid:         val.Uid,
		RefreshTime: val.RefreshTime,
		Mid:         val.Mid,
	}
	return
}

func FormatRecvRedPacketInfoSps(lst []*m.GetRedPacket) (r []*sp.GetRedPacket) {
	for _, item := range lst {
		r = append(r, FormatRecvRedPacketInfoSp(item))
	}
	return
}

func FormatRecvRedPacketInfoSp(val *m.GetRedPacket) (r *sp.GetRedPacket) {
	r = &sp.GetRedPacket{
		Mid:      val.Mid,
		RecvTime: val.RecvTime,
	}
	return
}

func FormatShopItemSps(mList map[int64]*m.ShopItem) (r []*sp.ShopItem) {
	for _, item := range mList {
		r = append(r, &sp.ShopItem{
			Tid:  item.Tid,
			Typ:  item.Typ,
			Num:  item.Num,
			Time: item.Time,
		})
	}
	return
}

func FormatShopItemSp(item *m.ShopItem) (r *sp.ShopItem) {
	return &sp.ShopItem{
		Tid:  item.Tid,
		Typ:  item.Typ,
		Num:  item.Num,
		Time: item.Time,
	}
}

func FormatMailsSps(list []*m.Mail) (r []*sp.Mail) {
	for _, item := range list {
		r = append(r, FormatMailSp(item))
	}
	return
}

func FormatMailSp(mail *m.Mail) (rMail *sp.Mail) {
	res := make([]*sp.Goods, 0)
	for _, item := range mail.Res {
		res = append(res, &sp.Goods{Tid: item.Tid, Num: item.Num})
	}
	return &sp.Mail{
		Id:      mail.Id.Hex(),
		Type:    mail.Type,
		Title:   mail.Title,
		Content: mail.Content,
		Time:    mail.Time,
		Status:  mail.Status,
		Res:     res,
	}
}

func FormatBoxResSps(list []*m.BoxRes) (r []*sp.BoxGoods) {
	for _, item := range list {
		r = append(r, &sp.BoxGoods{
			Tid: item.Tid,
			Res: FormatGoodsInfoSps(item.Res),
		})
	}
	return
}

func FormatEventMsgSps(list []*m.EventMsg) (r []*sp.EventMsg) {
	for _, item := range list {
		r = append(r, &sp.EventMsg{
			Id:          item.Id,
			Name:        item.Name,
			Head:        item.Head,
			Op:          item.Op,
			Value:       item.Value,
			Time:        item.Time,
			AvatarFrame: item.AvatarFrame,
		})
	}
	return
}

func FormatUnionRankSps(list []*m.UnionRank) (r []*sp.UnionRank) {
	for _, item := range list {
		r = append(r, &sp.UnionRank{
			Id:        item.RankId,
			UnionId:   item.UnionId,
			Name:      item.Name,
			ShortName: item.ShortName,
			Ico: &sp.UnionIco{
				Bottom: item.Ico.Bottom,
				Pic:    item.Ico.Pic,
			},
			Star: item.Star,
		})
	}
	return
}

func FormatUserRankSps(list []*m.UserRank) (r []*sp.UserRank) {
	for _, item := range list {
		r = append(r, &sp.UserRank{
			Id:          item.RankId,
			Uid:         item.Uid,
			Name:        item.Name,
			Head:        item.Head,
			Star:        item.Star,
			AvatarFrame: item.AvatarFrame,
		})
	}
	return
}

func FormatPetSps(mlist map[int64]*m.Pet) (r []*sp.Pet) {
	for _, item := range mlist {
		if !item.IsHave {
			continue
		}
		r = append(r, &sp.Pet{
			Tid:         item.Tid,
			Lv:          item.Lv,
			Exp:         item.Exp,
			Step:        item.Step,
			SkillVal:    int64(item.SkillVal * 1000),
			LiveEndTime: item.LiveEndTime,
			Status:      item.Status,
		})
	}
	return
}

func FormatPetSp(item *m.Pet) (r *sp.Pet) {
	if item == nil {
		return
	}
	return &sp.Pet{
		Tid:         item.Tid,
		Lv:          item.Lv,
		Exp:         item.Exp,
		Step:        item.Step,
		SkillVal:    int64(item.SkillVal * 1000),
		LiveEndTime: item.LiveEndTime,
		Status:      item.Status,
	}
}

func FormatBaseStaticSps(mlist map[int64]*m.Static) (r []*sp.BaseStatic) {
	for _, item := range mlist {
		r = append(r, &sp.BaseStatic{
			Typ: item.Typ,
			Num: item.Num,
		})
	}
	return
}

func FormatCardBuffSps(list []*m.CardBuff) (r []*sp.CardUserBuff) {
	for _, item := range list {
		r = append(r, &sp.CardUserBuff{
			Tid:      item.Tid,
			CardType: item.CardType,
			Round:    item.UseRound,
			Val:      item.Val,
			ShowVal:  item.ShowVal,
		})
	}
	return
}

func FormatCardSps(list []*m.Card) (r []*sp.Card) {
	for _, item := range list {
		r = append(r, &sp.Card{
			Tid:    item.Tid,
			Id:     item.Id,
			Status: item.Status,
		})
	}
	return
}

func FormatCardMonsterSkillSps(list map[int64]*m.CardMonsterSkill) (r []*sp.CardMonsterSkill) {
	for _, item := range list {
		r = append(r, &sp.CardMonsterSkill{
			Tid:       item.Tid,
			Cd:        item.Cd,
			Val:       item.Val,
			ExtVal:    item.ExtVal,
			ShowVal:   item.ShowValue,
			StayRound: item.StayRound,
		})
	}
	return
}

func FormatCardMonsterSp(monster *m.CardMonster) (r *sp.CardMonster) {
	return &sp.CardMonster{
		Tid:               monster.Tid,
		Hp:                monster.Hp,
		Shield:            monster.Shield,
		Skills:            FormatCardMonsterSkillSps(monster.Skills),
		HurtSum:           monster.HurtSum,
		Att:               monster.Att,
		AttBrustPermanent: monster.AttBrustPermanent,
		AttBrustHpPoint:   monster.AttBrustHpPoint,
	}
}

func FormatHurtAttrSps(list []*m.HurtAttr) (r []*sp.CardHurt) {
	for _, item := range list {
		hurtInfo := &sp.CardHurt{
			Tid:          item.Tid,
			Target:       item.Target,
			HurtType:     item.HurtType,
			Typ:          item.Typ,
			Val:          item.Val,
			ShieldHurt:   item.ShieldHurt,
			CanBloodSuck: item.CanBloodSuck,
			ValType:      item.ValType,
			Discard:      item.Discard,
		}
		hurtInfo.EffectBuff = make([]int64, 0)
		if item.EffectBuff != nil && len(item.EffectBuff) > 0 {
			for buffId, _ := range item.EffectBuff {
				hurtInfo.EffectBuff = append(hurtInfo.EffectBuff, buffId)
			}
		}
		if item.SpAtkTyp != nil && len(item.SpAtkTyp) > 0 {
			hurtInfo.SpAtkTyp = make([]int64, 0)
			for spEnumTid, _ := range item.SpAtkTyp {
				hurtInfo.SpAtkTyp = append(hurtInfo.SpAtkTyp, spEnumTid)
			}
		}
		r = append(r, hurtInfo)
	}
	return
}

func FormatCardGameKillMonsterSps(mlist map[int64]*m.CardGameKillMonster) (r []*sp.CardMonsterKill) {
	if mlist == nil {
		return
	}
	for tid, item := range mlist {
		r = append(r, &sp.CardMonsterKill{
			Tid:   tid,
			Round: item.Round,
		})
	}
	return
}

func FormatCardGameMagicBookInfo(m *m.MagicBook) (r *sp.CardMagicBookInfo) {
	if m == nil {
		return nil
	}
	r = &sp.CardMagicBookInfo{
		Typ:        m.Typ,
		Status:     m.Status,
		GridId:     m.GridId,
		ResetCount: m.ResetCount,
		CardLst:    make([]*sp.BaseKV, 0),
	}
	if m.CardLst != nil && len(m.CardLst) > 0 {
		for id, cardTid := range m.CardLst {
			r.CardLst = append(r.CardLst, &sp.BaseKV{
				Key: id,
				Val: cardTid,
			})
		}
	}
	return
}

func FormatCardGameCardDeckInfo(m *m.CardDeck) (r *sp.CardDeck) {
	if m == nil {
		return nil
	}
	r = &sp.CardDeck{
		LockBlockTid: m.LockBlockTid,
		ExtraCard:    make([]*sp.BaseKV, 0),
	}
	if m.ExtraCard != nil && len(m.ExtraCard) > 0 {
		for tid, num := range m.ExtraCard {
			r.ExtraCard = append(r.ExtraCard, &sp.BaseKV{
				Key: tid,
				Val: num,
			})
		}
	}
	return
}

// 放火事件仇人信息
func FormatSlotFoeMemberSps(list []*m.FoeMember) (r []*sp.FoeMember) {
	for _, item := range list {
		v, ok := m.Cache.Get("user", item.Uid)
		if !ok {
			continue
		}
		user := v.(*m.User)
		foeMember := &sp.FoeMember{
			UserInfo: FormatSimpleUser(user),
			Time:     item.Time,
		}
		r = append(r, foeMember)
	}
	return
}

// 广告奖励信息
func FormatAdRewardSps(list []*m.AdReward) (r []*sp.AdReward) {
	nowTime := utils.TNow().Unix()
	for _, item := range list {
		if utils.IsSameDay(item.Time, nowTime) {
			r = append(r, FormatAdRewardSp(item))
		}

	}
	return
}

// 广告奖励信息
func FormatAdRewardSp(item *m.AdReward) (r *sp.AdReward) {
	if item == nil {
		return
	}

	return &sp.AdReward{
		Typ:      item.Typ,
		WatchNum: item.WatchNum,
		Time:     item.Time,
	}
}

// 占卜Buff信息
func FormatScryBuffList(mlist map[int64]*m.ScryBuffInfo) (r []*sp.ScryBuff) {
	if mlist == nil {
		return
	}
	for tid, item := range mlist {
		r = append(r, &sp.ScryBuff{
			Id:        tid,
			Typ:       item.Typ,
			EndTime:   item.EndTime,
			LeftCount: item.LeftCount,
			Val:       int64(item.Val * 10), // 乘以10倍返回给客户端
		})
	}
	return
}

func FormatAvatarFramesArr(input map[int64]int64) (r []int64) {
	for _, val := range input {
		r = append(r, val)
	}
	return
}

// 活动进度列表
func FormatUserActProgressList(mlist map[int64]*m.SingleActivityProgress) (r []*sp.UserActivityProgress) {
	if mlist == nil {
		return
	}
	for actID, item := range mlist {
		r = append(r, &sp.UserActivityProgress{
			ActivID:           actID,
			CurRound:          item.CurRound,
			CurRoundItemCount: item.CurRoundItemCount,
			TotalItemCount:    item.TotalItemCount,
			GainRoundReward:   item.GainRoundReward,
			Close:             item.Close,
			RankId:            item.RankId,
		})
	}
	return
}

// 活动列表推送
// func FormatTotalActActivity(dMap map[int64]map[int64]*m.ActActivityInfo) (slotActP []*sp.ActivityInfo, loginActP []*sp.ActivityInfo, bossCombatActP []*sp.ActivityInfo, otherActP []*sp.ActivityInfo, JackpotActP []*sp.ActivityInfo, CollectionActP []*sp.ActivityInfo) {
// 	if dMap == nil {
// 		dMap = make(map[int64]map[int64]*m.ActActivityInfo)
// 	}
// 	slotActP = make([]*sp.ActivityInfo, 0)       // 老虎机活动列表
// 	loginActP = make([]*sp.ActivityInfo, 0)      //登录活动列表
// 	bossCombatActP = make([]*sp.ActivityInfo, 0) //世界BOSS活动列表
// 	otherActP = make([]*sp.ActivityInfo, 0)      // 其他活动列表
// 	JackpotActP = make([]*sp.ActivityInfo, 0)    // 彩金活动
// 	CollectionActP = make([]*sp.ActivityInfo, 0) // 彩金活动
// 	if len(dMap) > 0 {
// 		for _, typeList := range dMap {
// 			for _, act := range typeList {
// 				tType := WhatIsActEnum(act.ActId)
// 				switch tType {
// 				case data.ActivityEnum.Slot:
// 					slotActP = append(slotActP, &sp.ActivityInfo{
// 						ActivID:      act.ActId,
// 						ActTypEnum:   act.TypeEnum,
// 						BeginTime:    act.BeginTime,
// 						EndTime:      act.EndTime,
// 						ResetMonth:   act.ResetMonth,
// 						ResetWeekDay: act.ResetWeekDay,
// 					})
// 				case data.ActivityEnum.Login:
// 					loginActP = append(loginActP, &sp.ActivityInfo{
// 						ActivID:      act.ActId,
// 						ActTypEnum:   act.TypeEnum,
// 						BeginTime:    act.BeginTime,
// 						EndTime:      act.EndTime,
// 						ResetMonth:   act.ResetMonth,
// 						ResetWeekDay: act.ResetWeekDay,
// 					})
// 				case data.ActivityEnum.BossCombat:
// 					bossCombatActP = append(bossCombatActP, &sp.ActivityInfo{
// 						ActivID:      act.ActId,
// 						ActTypEnum:   act.TypeEnum,
// 						BeginTime:    act.BeginTime,
// 						EndTime:      act.EndTime,
// 						ResetMonth:   act.ResetMonth,
// 						ResetWeekDay: act.ResetWeekDay,
// 					})
// 				case data.ActivityEnum.Jackpot:
// 					JackpotActP = append(JackpotActP, &sp.ActivityInfo{
// 						ActivID:      act.ActId,
// 						ActTypEnum:   act.TypeEnum,
// 						BeginTime:    act.BeginTime,
// 						EndTime:      act.EndTime,
// 						ResetMonth:   act.ResetMonth,
// 						ResetWeekDay: act.ResetWeekDay,
// 					})
// 				case data.ActivityEnum.Christmas:
// 					CollectionActP = append(CollectionActP, &sp.ActivityInfo{
// 						ActivID:      act.ActId,
// 						ActTypEnum:   act.TypeEnum,
// 						BeginTime:    act.BeginTime,
// 						EndTime:      act.EndTime,
// 						ResetMonth:   act.ResetMonth,
// 						ResetWeekDay: act.ResetWeekDay,
// 					})
// 				default:
// 					otherActP = append(otherActP, &sp.ActivityInfo{
// 						ActivID:      act.ActId,
// 						ActTypEnum:   act.TypeEnum,
// 						BeginTime:    act.BeginTime,
// 						EndTime:      act.EndTime,
// 						ResetMonth:   act.ResetMonth,
// 						ResetWeekDay: act.ResetWeekDay,
// 					})
// 				}
// 			}
// 		}
// 	}
// 	return slotActP, loginActP, bossCombatActP, otherActP, JackpotActP, CollectionActP
// }
func FormatTotalActActivity(dMap map[int64]map[int64]*m.ActActivityInfo) (activityAll []*sp.ActivityInfo) {
	if dMap == nil {
		dMap = make(map[int64]map[int64]*m.ActActivityInfo)
	}
	activityAll = make([]*sp.ActivityInfo, 0) // 老虎机活动列表
	if len(dMap) > 0 {
		for _, typeList := range dMap {
			for _, act := range typeList {
				activityAll = append(activityAll, &sp.ActivityInfo{
					ActivID:      act.ActId,
					ActTypEnum:   act.TypeEnum,
					BeginTime:    act.BeginTime,
					EndTime:      act.EndTime,
					ResetMonth:   act.ResetMonth,
					ResetWeekDay: act.ResetWeekDay,
				})
			}
		}
	}
	return
}

func FormatEntrActiv(activ *data.EntrustActiv) (r *sp.ActivityInfo) {
	beginTime, _ := utils.LayoutToTime(activ.BeginTime)
	endTime, _ := utils.LayoutToTime(activ.EndTime)
	r = &sp.ActivityInfo{
		ActivID:    int64(activ.Id),
		ActTypEnum: data.ActivityEnum.Entrust,
		BeginTime:  beginTime.Unix(),
		EndTime:    endTime.Unix(),
	}
	return
}

// 活动排名
func FormatActRankLst(dMap map[string]*m.UserActRank) (r []*sp.ActivityRank) {
	if dMap == nil {
		return
	}
	for _, rankData := range dMap {
		r = append(r, &sp.ActivityRank{
			Rank:           rankData.RankId,
			Uid:            rankData.Uid,
			Name:           rankData.Name,
			Head:           rankData.Head,
			AvatarFrame:    rankData.AvatarFrame,
			TotalItemCount: rankData.Item,
		})
	}
	return r
}

// 活动排名
func FormatActRankBossLst(lst []*m.MCGamer) (r []*sp.ActivityRank) {
	if lst == nil {
		return
	}
	for _, rankData := range lst {
		r = append(r, &sp.ActivityRank{
			Rank:           rankData.RankId,
			Uid:            rankData.Uid.Hex(),
			Name:           rankData.Name,
			Head:           rankData.Head,
			AvatarFrame:    rankData.AvatarFrame,
			TotalItemCount: rankData.Hurt,
		})
	}
	return r
}

func FormatMulCombatBossLst(lst []*sp.MulCombatBossState) (r []*sp.MulCombatBossState) {
	if lst == nil {
		return
	}
	return r
}

func FormatBaseKVLst(m map[int64]int64) (r []*sp.BaseKV) {
	r = make([]*sp.BaseKV, 0)
	for key, val := range m {
		r = append(r, &sp.BaseKV{Key: key, Val: val})
	}
	return
}

func FormatSpBoxContent(u *m.User, m map[int64]*m.SpecialBoxContent) (r []*sp.SpecialBoxContent) {
	if m == nil {
		return
	}

	for _, theData := range m {
		theContent := &sp.SpecialBoxContent{
			Tid: theData.Tid,
		}
		theContent.CardLst = make([]*sp.SpecialBoxGood, 0)
		if theData.Goods != nil && len(theData.Goods) > 0 {
			for _, good := range theData.Goods {
				theGoodInfo := &sp.SpecialBoxGood{
					Id:    good.Id,
					Tid:   good.Tid,
					IsNew: 0,
				}
				ok := HasHeroGood(u, good.Tid)
				if ok {
					theGoodInfo.IsNew = 1
				}

				theContent.CardLst = append(theContent.CardLst, theGoodInfo)

			}

		}
		r = append(r, theContent)
	}
	return
}

func FormatEntrGamerLst(lst []*m.ERGamer) (r []*sp.EntrGamer) {
	r = make([]*sp.EntrGamer, 0)
	for _, item := range lst {
		eg := &sp.EntrGamer{
			RankId:      item.RankId,
			Uid:         item.Uid.Hex(),
			Name:        item.Name,
			Head:        item.Head,
			AvatarFrame: item.AvatarFrame,
			Honor:       item.Honor,
		}
		r = append(r, eg)
	}
	return
}

func FormatEntrustInfo(ea *m.EntrustTask) (r *sp.EntrustInfo) {
	lst := make([]*sp.StageInfo, 0)
	for _, item := range ea.StageLst {
		si := &sp.StageInfo{
			Stage: item.StageVal,
			Tid:   item.GoodTid,
			Num:   item.GoodNum,
			State: item.State,
		}
		lst = append(lst, si)
	}
	r = &sp.EntrustInfo{
		Tid: ea.Tid,
		Lst: lst,
	}
	return
}

func FormatHeroInfoSps(hero *m.Hero) (r *sp.Hero) {
	hGoods := make([]*sp.HeroGoods, 0)
	for _, item := range hero.Goods {
		hGoods = append(hGoods, &sp.HeroGoods{Tid: item.Tid, Num: item.Num, Star: item.Star})
	}
	r = &sp.Hero{
		Tid:     hero.Tid,
		Goods:   hGoods,
		SkillId: hero.SkillId,
	}
	return
}

func FormatHeroListSps(list []*m.Hero) (r []*sp.Hero) {
	r = make([]*sp.Hero, 0)
	for _, val := range list {
		hero := FormatHeroInfoSps(val)
		r = append(r, hero)
	}
	return
}

func FormatUserFriendsData(fData *m.UserFriends) (r *sp.FriendsData) {
	fLst := make([]*sp.UserFriend, 0)

	if fData.FriendsLst != nil && len(fData.FriendsLst) > 0 {
		for _, theFriend := range fData.FriendsLst {
			theUser, ok := globalFunc.GetUserByUID(theFriend.Uid)
			if ok {
				// var starSum int64 = theUser.Star + theUser.StarHero + theUser.StarMap + theUser.StarPet
				var IsOnLine int64 = 0
				if theUser.IsOnLine() == false {
					IsOnLine = 1
				}
				fInfo := &sp.UserFriend{
					Uid:            theFriend.Uid,
					Name:           theUser.Name,
					Head:           theUser.Head,
					AvatarFrame:    theUser.AvatarFrame,
					Star:           theUser.StarVal(),
					Gold:           theUser.Gold,
					ReciveCount:    theFriend.ReciveCount,
					ReciveRecord:   theFriend.ReciveRecord,
					SendCount:      theFriend.SendCount,
					LastSignInTime: theUser.LastLoginTime, // 上次登录时间
					IsOnLine:       IsOnLine,              // 0-上线 1-下线
					Pos: &sp.PosInfo{
						LockBlockTid: theUser.Pos.LockBlockTid,
						LayerId:      theUser.Pos.LayerId,
					},
				}
				fLst = append(fLst, fInfo)
			}
		}
	}

	r = &sp.FriendsData{
		InviteFriendNum:   fData.InviteFriendNum,
		SendRecord:        fData.SendRecord,
		ReciveRecord:      fData.ReciveRecord,
		TotalReciveNum:    fData.TotalReciveNum,
		DailyReqFriendNum: fData.DailyReqFriendNum,
		FriendsLst:        fLst,
	}
	return
}

func FormatSimpleFriend(u *m.User) (r *sp.SimpleFriendData) {
	if u == nil {
		return
	}
	r = &sp.SimpleFriendData{
		Uid:         u.Uid.Hex(),
		Name:        u.Name,
		Head:        u.Head,
		AvatarFrame: u.AvatarFrame,
		Star:        u.StarVal(),
		Gold:        u.Gold,
	}
	return
}

func FormatSimpleFriendLst(lst []*m.User) (r []*sp.SimpleFriendData) {
	r = make([]*sp.SimpleFriendData, 0)
	for _, item := range lst {
		sfd := &sp.SimpleFriendData{
			Uid:         item.Uid.Hex(),
			Name:        item.Name,
			Head:        item.Head,
			AvatarFrame: item.AvatarFrame,
			Star:        item.StarVal(),
			Gold:        item.Gold,
		}
		r = append(r, sfd)
	}
	return
}

func FormatSimpleFriendsDat(lst map[string]*m.ReqFriendData) (r []*sp.SimpleFriendData) {
	r = make([]*sp.SimpleFriendData, 0)
	if lst != nil && len(lst) > 0 {
		for uid, _ := range lst {
			theUser, ok := globalFunc.GetUserByUID(uid)
			if ok {
				fInfo := &sp.SimpleFriendData{
					Uid:         theUser.Uid.Hex(),
					Name:        theUser.Name,
					Head:        theUser.Head,
					AvatarFrame: theUser.AvatarFrame,
					Star:        theUser.StarVal(),
					Gold:        theUser.Gold,
				}
				r = append(r, fInfo)
			}
		}
	}
	return
}

// 封装成就信息
func FormatAchievInfoSps(u *m.User) (r []*sp.Achiev) {
	ua, _ := u.GetUserAchiev(u.Uid.Hex())
	r = make([]*sp.Achiev, 0)
	for _, item := range ua.AchievInfos {
		achiev := &sp.Achiev{
			AchievType: item.AchievType,
			Progress:   item.Progress,
		}
		idxF := -1
		for idx, itemL := range item.AchievLst {
			if item.Progress < itemL.Progress { // 当前进度 < 阀值，结束循环
				break
			} else { //当前进度>=阀值
				if itemL.State == 1 { //这个阶段状态为，激活状态，奖励未领取。
					idxF = idx
					break
				}
			}
		}
		// 找到未领取的成就
		if idxF < 0 {
			// 未找到领取的成就，剩余情况：1、都为完成就。2、成就都完成了。3、成就完成和未完成
			for idx, itemL := range item.AchievLst {
				if itemL.State == 0 { //这个阶段状态为，未激活成就
					idxF = idx
					break
				}
			}
			if idxF < 0 { // 所有成就都完成了
				idxF = len(item.AchievLst) - 1
			}
			// 找到未完成的成就。
		}
		achiev.Tid = item.AchievLst[idxF].Tid
		achiev.State = item.AchievLst[idxF].State
		switch item.AchievType {
		case data.AchievementType.Progress_card:
			achiev.Progress = 0
			if achiev.State > 0 {
				achiev.Progress = 1
			}
		case data.AchievementType.DiffLevel_pet:
			achiev.Progress = 0
			if achiev.State > 0 {
				achiev.Progress = 4
			}
		case data.AchievementType.Get_HideLevelCards:
			achiev.Progress = 0
			if achiev.State > 0 {
				achiev.Progress = 1
			}
		}

		r = append(r, achiev)
	}
	return
}

// 封装单个成就信息
func FormatAchievInfoSp(u *m.User, tid int64, achType int64) (r []*sp.Achiev) {
	ua, _ := u.GetUserAchiev(u.Uid.Hex())
	r = make([]*sp.Achiev, 0)

	if val, ok := ua.AchievInfos[achType]; ok {
		achiev := &sp.Achiev{
			AchievType: val.AchievType,
			Progress:   val.Progress,
		}
		idxF := 0
		for idx, item := range val.AchievLst {
			if item.Tid == tid {
				idxF = idx
				break
			}
		}
		if idxF+1 < len(val.AchievLst) {
			idxF += 1
		}
		achiev.Tid = val.AchievLst[idxF].Tid
		achiev.State = val.AchievLst[idxF].State
		switch val.AchievType {
		case data.AchievementType.Progress_card:
			achiev.Progress = 0
			if achiev.State > 0 {
				achiev.Progress = 1
			}
		case data.AchievementType.DiffLevel_pet:
			achiev.Progress = 0
			if achiev.State > 0 {
				achiev.Progress = 4
			}
		case data.AchievementType.Get_HideLevelCards:
			achiev.Progress = 0
			if achiev.State > 0 {
				achiev.Progress = 1
			}
		}
		r = append(r, achiev)
	}
	return
}

// 封装 累计成就
func FormatAchievTotalSp(u *m.User) (r *sp.AchievTotal) {
	at, _ := u.GetAchievTotal(u.Uid.Hex())
	r = &sp.AchievTotal{
		Tid:        at.Tid,
		StarCur:    at.StarCur,
		StarAchiev: at.StarAchiev,
	}
	return
}

func FormatRecruitTrainSps(lst []*m.RTState) (r []*sp.RTState) {
	r = make([]*sp.RTState, 0)
	fidx := -1
	for idx, item := range lst {
		if item.State == 2 {
			fidx = idx
		}
	}
	if fidx < 0 {
		fidx = 0
	} else {
		fidx++
	}

	for idx, item := range lst {
		if idx <= fidx {
			r = append(r, &sp.RTState{
				Tid:          item.Tid,
				LevelState:   item.LevelState,
				StarState:    item.StarState,
				MonsterState: item.MonsterState,
				State:        item.State,
			})
		} else {
			r = append(r, &sp.RTState{
				Tid:          item.Tid,
				LevelState:   item.LevelState,
				StarState:    item.StarState,
				MonsterState: item.MonsterState,
			})
		}
	}
	return
}

func FormatRTState(rts *m.RTState) (r *sp.RTState) {
	if rts == nil {
		return
	}
	r = &sp.RTState{
		Tid:          rts.Tid,
		LevelState:   rts.LevelState,
		StarState:    rts.StarState,
		MonsterState: rts.MonsterState,
		State:        rts.State,
	}
	return
}

func FormatJackpotRank(lst []*m.JGamer) (r []*sp.JackpotPlayer) {
	r = make([]*sp.JackpotPlayer, 0)
	for _, item := range lst {
		r = append(r, &sp.JackpotPlayer{
			Uid:         item.Uid.Hex(),
			Name:        item.Name,
			Head:        item.Head,
			AvatarFrame: item.AvatarFrame,
			Amount:      item.Amount,
			Jtype:       item.Jtype,
			Time:        item.Time,
		})
	}
	return
}

func FormatJackpotGamer(g *m.JGamer) (r *sp.JackpotPlayer) {
	if g == nil {
		return
	}
	r = &sp.JackpotPlayer{
		Uid:         g.Uid.Hex(),
		Name:        g.Name,
		Head:        g.Head,
		AvatarFrame: g.AvatarFrame,
		Amount:      g.Amount,
		Jtype:       g.Jtype,
		Time:        g.Time,
	}
	return
}

func FormatChristmasTree(uChristmasTree *m.UserChristmasTree) (r *sp.ChristmasTree) {
	if uChristmasTree == nil {
		return
	}
	r = &sp.ChristmasTree{
		Level:    uChristmasTree.Level,
		Ball:     uChristmasTree.Ball,
		Candy:    uChristmasTree.Candy,
		Stocking: uChristmasTree.Stocking,
	}
	if val, ok := uChristmasTree.Tree[uChristmasTree.Level]; ok {
		r.State = val.State
	}
	return
}

func FormatColloctProp(uColloctProp *m.UserColloctProp) (r *sp.ColloctProp) {
	if uColloctProp == nil {
		return
	}
	prop := make([]*sp.BaseKV, 0)
	for key, val := range uColloctProp.MProp {
		prop = append(prop, &sp.BaseKV{
			Key: key,
			Val: val,
		})
	}
	r = &sp.ColloctProp{
		ActivId: uColloctProp.ActivId,
		Level:   uColloctProp.Level,
		Prop:    prop,
		State:   uColloctProp.State,
	}
	return
}
